let express = require("express");
let uunewid = require("uuid");
let router = express.Router();
let moment = require("moment");
let constants = require("../utils/constants");
let log = require("cf-nodejs-logging-support");
log.setLoggingLevel("info");
const axios = require("axios");
const md5 = require("md5");

const { ohana } = require("ohana-node-orm");
const ohana_instance = new ohana(constants.VERIFYCODETABLE);
const ohana_instance_user = new ohana(constants.REGISTEDUSERSTABLE);

router.post("/verifySubaccountCode", function (req, res, next) {
    // #swagger.tags = ['验证手机短信']
    // #swagger.summary = '发送手机验证码'
    // #swagger.description = '需要JWT Token'
    /* #swagger.security = [{
                   "JiangduJWT": []
      }] */
    // get phone
    const { data } = req.body;
    if (!data.phone || !data.code) {
        res.status(400).send({ code: -1, message: "请输入验证码" });
    }
    checkIfRegistered(data.phone).then(result => {
        console.log(result);
        if (result) {
            verifySubCode(data).then((result) => {
                console.log(result)
                if (result <= 0) {
                    var sendText = "";
                    sendText =
                        "【江都企业数字赋能平台】子账户手机验证已经通过 " +
                        data.phone
                    const urlParams =
                        "?action=send&account=922569&password=pe6Zxa&mobile=" +

                        data.phone +
                        "&content=" +
                        encodeURI(sendText) +
                        "&extno=106901569&rt=json";
                    axios({
                        method: "post",
                        url: "http://114.218.57.125:7862/sms" + urlParams,
                    })
                        .then(() => {
                            res.send({ code: 0, message: "已验证" });
                        })
                        .catch((err) => {
                            console.log(err);
                            res.send(err);
                        });
                } else {
                    res.status(400).send({ code: -1, message: "验证码错误或者已过期" });
                }
            });
        } else {
            res.status(400).send({ code: -1, message: "手机号已注册" });
        }
    })

})

async function checkIfRegistered(phone) {
    const result = await ohana_instance_user.find({ PHONE: phone });
    if (result.length > 0) {
        //有人注册过
        return false;
    } else {
        //无人注册
        return true;
    }

}

router.post("/sendCode", function (req, res, next) {
    // #swagger.tags = ['验证手机短信']
    // #swagger.summary = '发送手机验证码'
    // #swagger.description = '需要JWT Token'
    /* #swagger.security = [{
                   "JiangduJWT": []
      }] */
    // get phone

    const { data } = req.body;
    if (!data.phone && !phoneCheck(data.phone)) {
        res.status(400).send({ message: "手机格式错误", code: -1 });
    }
    const initialCode = generateCode().toString();
    var sendText =
        "【江都企业数字赋能平台】手机注册验证码：" +
        initialCode +
        "，验证码有效时间为5分钟";
    const urlParams =
        "?action=send&account=922569&password=pe6Zxa&mobile=" +
        data.phone +
        "&content=" +
        encodeURI(sendText) +
        "&extno=106901569&rt=json";
    axios({
        method: "post",
        url: "http://114.218.57.125:7862/sms" + urlParams,
    })
        .then(() => {

            const validationDate = moment().add(59, "s").format();
            ohana_instance.updateOrCreate(
                { PHONE: data.phone },
                { CONTENT: initialCode, DATE: validationDate }
            );
            res.sendStatus(200);
        })
        .catch((err) => {
            console.log(err);
            res.send(err);
        });
});

router.post("/verifyCode", function (req, res, next) {
    // #swagger.tags = ['验证手机短信']
    // #swagger.summary = '验证手机验证码'
    // #swagger.description = '需要JWT Token'
    /* #swagger.security = [{
                   "JiangduJWT": []
      }] */
    const { data } = req.body;
    if (!data.phone || !data.code) {
        res.status(400).send({ code: -1, message: "参数错误" });
    }
    verifyCode(data).then((result) => {
        if (result <= 0 && result >= -5) {
            var sendText = "";
            if (data.mode == "initial") {
                sendText =
                    "【江都企业数字赋能平台】扫码微信小程序，进行法人人脸核验，完成注册最后一步。用户名: " +
                    data.phone +
                    ", 初始密码: " +
                    data.code +
                    "，未认证账号有效期1天。";
                const urlParams =
                    "?action=send&account=922569&password=pe6Zxa&mobile=" +
                    data.phone +
                    "&content=" +
                    encodeURI(sendText) +
                    "&extno=106901569&rt=json";
                axios({
                    method: "post",
                    url: "http://114.218.57.125:7862/sms" + urlParams,
                })
                    .then(() => {
                        ohana_instance_user
                            .update({ USER_NAME: data.phone }, { PASSWORD: md5(data.code) })
                            .then((result) => {
                                if (result > 0) {
                                    res.send({ code: 0, message: "注册人工审核用户" });
                                } else {
                                    res.send({ code: 0, message: "注册新用户" });
                                }
                            });
                    })
                    .catch((err) => {
                        console.log(err);
                        res.send(err);
                    });
            } else if (data.mode == "edit") {
                sendText =
                    "【江都企业数字赋能平台】您正在修改密码。用户名: " +
                    data.phone +
                    "你的新密码为：" +
                    data.code;
                const urlParams =
                    "?action=send&account=922569&password=pe6Zxa&mobile=" +
                    data.phone +
                    "&content=" +
                    encodeURI(sendText) +
                    "&extno=106901569&rt=json";
                axios({
                    method: "post",
                    url: "http://114.218.57.125:7862/sms" + urlParams,
                })
                    .then(() => {
                        ohana_instance_user
                            .update({ USER_NAME: data.phone }, { PASSWORD: md5(data.code) })
                            .then((result) => {
                                if (result > 0) {
                                    res.send({ code: 0, message: "OK" });
                                } else {
                                    res.status(400).send({ message: "找不到用户", code: -2 });
                                }
                            });
                        //res.sendStatus(200);
                    })
                    .catch((err) => {
                        console.log(err);
                        res.send(err);
                    });
            }
            // res.send({ code: 0, message: "OK" })
        } else {
            res.status(400).send({ code: -1, message: "验证码错误或者已过期" });
        }
    });
});
async function verifyCode(data) {
    const result = await ohana_instance.findOne({
        PHONE: data.phone,
        CONTENT: data.code,
    });
    if (result.length > 0) {
        const currentDate = moment();
        // console.log(currentDate.diff(result[0].DATE, "m"))
        return currentDate.diff(result[0].DATE, "m");
    }
    return 99;
}
async function verifySubCode(data) {
    const result = await ohana_instance.findOne({
        PHONE: data.phone,
        CONTENT: data.code,
    });
    if (result.length > 0) {
        const currentDate = moment();
        // console.log(currentDate.diff(result[0].DATE, "m"))
        return currentDate.diff(result[0].DATE, "s");
    }
    return 99;
}
function generateCode() {
    return Math.random().toFixed(6).slice(-6);
}
function phoneCheck(tels) {
    var myreg = /^(([0\+]\d{2,3}-)?(0\d{2,3})-)(\d{7,8})(-(\d{3,}))?$/;
    if (!myreg.test(tels)) {
        return false;
    } else {
        return true;
    }
}

router.post("/generalSMS", function (req, res, next) {
    // #swagger.tags = ['验证手机短信']
    // #swagger.summary = '人脸识别结束发短信'
    // #swagger.description = '参数为Text已经phone'
    /* #swagger.security = [{
                   "JiangduJWT": []
      }] */
    // get phone

    const { data } = req.body;
    if (!data.phone && !phoneCheck(data.phone)) {
        res.status(400).send({ message: "手机格式错误", code: -1 });
    }
    var sendText = "【江都企业数字赋能平台】" + data.text;
    const urlParams =
        "?action=send&account=922569&password=pe6Zxa&mobile=" +
        data.phone +
        "&content=" +
        encodeURI(sendText) +
        "&extno=106901569&rt=json";
    axios({
        method: "post",
        url: "http://114.218.57.125:7862/sms" + urlParams,
    })
        .then(() => {
            res.sendStatus(200);
        })
        .catch((err) => {
            console.log(err);
            res.send(err);
        });
});

module.exports = router;
